<template>
  <div class="user">
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="5" class="user__tree">

          <avue-tree style="height: 500px;overflow-y: auto;" :option="treeOption" :data="treeData" @node-click="nodeClick"/>
        </el-col>
        <el-col :xs="24" :sm="24" :md="19" class="user__main">
          <avue-crud ref="crud" :option="option" v-model="form" :page="page" :table-loading="listLoading" :before-open="handleOpenBefore" :data="list" @on-load="getList" @search-change="handleFilter" @refresh-change="handleRefreshChange" @row-update="update" @row-save="create">
            <template slot="menuLeft">
              <el-button v-if="sys_user_add" class="filter-item" type="primary" size="mini" icon="el-icon-edit"
                         @click="handleCreate">添加
              </el-button>
            </template>
            <template slot="username" slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
            <template slot="realName" slot-scope="scope">
              <span>{{ scope.row.realName }}</span>
            </template>
            <template slot="org" slot-scope="scope">
              <span v-for="(orgs,index) in scope.row.orgList" :key="index">
                <el-tag>{{ orgs.name }}</el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="role" slot-scope="scope">
<!--              <span>{{ scope.row.roleId }}</span>-->
              <span v-for="(role,index) in scope.row.rolesOptions" :key="index">
                <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="deptId" slot-scope="scope">
              {{ scope.row.deptName }}
            </template>
						<template slot="hisWorkNumer" slot-scope="scope">
						  {{ scope.row.hisWorkNumber }}
						</template>
            <template slot="unitId" slot-scope="scope">
              {{ scope.row.unitName }}
            </template>
            <template slot="jobType" slot-scope="scope">
              {{ valueToName(scope.row.jobType) }}
            </template>
            <template slot="posId" slot-scope="scope">
              {{ scope.row.posName }}
            </template>
            <template slot="lockFlag" slot-scope="scope">
              <el-tag>{{ scope.label }}</el-tag>
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button v-if="sys_user_edit" type="text" size="mini" icon="el-icon-s-home"
                         @click="orgUpdate(scope.row,scope.index)">
                组织
              </el-button>
              <el-button v-if="sys_user_edit" type="text" size="mini" icon="el-icon-edit"
                         @click="handleUpdate(scope.row,scope.index)">
                编辑
              </el-button>
              <el-button v-if="sys_user_del" type="text" size="mini" icon="el-icon-delete"
                         @click="deletes(scope.row,scope.index)">删除
              </el-button>
            </template>
            <template slot="deptIdForm" slot-scope="scope">
              <avue-input v-model="form.deptId" :dic="treeDeptData" :props="defaultProps" :node-click="getNodeData"
                          type="tree" placeholder="请选择所属部门"/>
            </template>
            <template slot="unitIdForm" slot-scope="scope">
              <avue-select v-model="form.unitId" :dic="unitOptions" :props="defaultProps" placeholder="请选择单位"/>
            </template>
            <template slot="jobTypeForm" slot-scope="scope">
              <avue-select multiple v-model="form.jobType" :dic="jobTypeOptions" :props="jobDefaultProps"
                type="tree" placeholder="请选择岗位类型"/>
            </template>
            <template
              slot="roleForm"
              slot-scope="scope">
              <avue-select
                multiple
                v-model="form.role"
                :dic="rolesOptions"
                :props="roleProps"
                type="tree"
                placeholder="请选择角色"/>
            </template>
            <template slot="posIdForm" slot-scope="scope">
              <avue-select v-model="form.posId" :dic="posOptions" :props="defaultProps" placeholder="请选择岗位"/>
            </template>
            <!-- <template
              slot="orgForm"
              slot-scope="scope"
              >
              <avue-input
                v-model="org"
                :dic="orgsOptions"
                :check-strictly="false"
                :props="defaultProps"
                type="tree"
                multiple
                placeholder="请选择组织"
                />
            </template> -->

          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
    <el-dialog :visible.sync="dialogPermissionVisible" :close-on-click-modal="false" title="分配组织">
      <div class="dialog-main-tree">
        <el-tree ref="orgTree" :data="treeData" :default-checked-keys="checkedKeys" :check-strictly="false"
                 :props="defaultProps"
                 class="filter-tree" node-key="id" highlight-current show-checkbox default-expand-all/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="updatePermession(userId)">更 新
        </el-button>
        <el-button type="default" size="small" @click="cancal()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {addObj, delObj, fetchList, putObj, getDetails, updateUserOrg} from '@/api/admin/user'
    import {unitList} from '@/api/admin/unit'
    import {posQuery} from '@/api/admin/pos'
    import {getInfoList} from '@/api/admin/jobtype'
    import {deptRoleList, getObj} from '@/api/admin/role'
    import {orgRoleList, fetchOrg} from '@/api/admin/org'
    import {fetchTree} from '@/api/admin/dept'
    import {tableOption} from '@/const/crud/admin/user'
    import {mapGetters} from 'vuex'

    import {log} from 'util'

    export default {

        name: 'SysUser',
        data() {
            return {
                userId: '',
                searchForm: {},
                treeOption: {
                    nodeKey: 'id',
                    addBtn: false,
                    menu: false,
                    props: {
                        label: 'name',
                        value: 'id'
                    }
                },
                treeData: [],
                option: tableOption,
                treeDeptData: [],
                checkedKeys: [],
                jobDefaultProps: {
                  label: 'jobName',
                  value: 'id'
                },

                defaultProps: {
                    label: 'name',
                    value: 'id'
                },
                roleProps: {
                    label: 'roleName',
                    value: 'roleId'
                },

                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条,
                    isAsc: false // 是否倒序
                },
                role: [],
                rolesOptions: [],

                list: [],
                listLoading: true,
                org: [],
                form: {
                    org: [],
                    unit: []
                },
                orgsOptions: [],
                unitOptions: [],
                jobTypeOptions: [],
                posOptions: [],
                dialogPermissionVisible: false
            }
        },
        computed: {
            ...mapGetters(['permissions'])
        },
        watch: {
            org() {
                this.form.org = this.org;
            },
            role() {
                this.form.role = this.role
            }
        },
        created() {
            this.sys_user_add = this.permissions['sys_user_add']
            this.sys_user_edit = this.permissions['sys_user_edit']
            this.sys_user_del = this.permissions['sys_user_del']
            this.init()
            //this.unitObtain()
            this.getJobTypeList()
        },
        methods: {

            init() {
                //获取树结构
                fetchTree().then(response => {
                    this.treeData = response.data.data
                })
                this.getRoleListData()
            },
            nodeClick(data) {
                this.page.page = 1
                this.deptId = data.id
                this.getList(this.page)
            },
            getList(page) {
                this.listLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    deptId: this.deptId
                }, this.searchForm)).then(response => {
                    let list = response.data.data.records
                    list.forEach(item => {
                        let rolesOptions = []
                        if(item.roleId){
                            let idList = item.roleId.split(',')

                            for(let i = 0; i < idList.length;i++){
                                let obj = this.rolesOptions.find(item => {
                                    return item.roleId == idList[i]
                                })
                                rolesOptions.push(obj)
                            }
                        }
                        console.log(rolesOptions)
                        item.rolesOptions = rolesOptions
                      if(item.jobType){
                        item.jobType = item.jobType.split(',')
                        for(let i = 0; i < item.jobType.length; i++){
                          item.jobType[i] = item.jobType[i]*1
                        }
                      }
                    })
                    this.list = [...list]
                    this.page.total = response.data.data.total
                    this.listLoading = false;
                })
            },
            getNodeData() {
                fetchOrg().then(response => {
                    this.orgsOptions = response.data.data;
                })
                this.getRoleListData()
            },
            getRoleListData() {
                deptRoleList().then(response => {
                    this.rolesOptions = response.data.data
                })
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize
            },
            currentChange(current) {
                this.page.currentPage = current
            },
            getUnitListData() {
                unitList().then(response => {
                    this.unitOptions = response.data.data;
                })
            },
            // 获取岗位类型
            getJobTypeList(){
              getInfoList().then(result => {
                console.log(result.data.data)
                this.jobTypeOptions = result.data.data
              })
            },
            getPosListData() {
                let params = {
                    current: 1,
                    size: 100
                }
                posQuery(params).then(result => {
                    this.posOptions = result.data.data.records
                })
            },
            handleDept() {
                fetchTree().then(response => {
                    this.treeDeptData = response.data.data
                })
            },
            handleFilter(param) {
                this.searchForm = param
                this.getList(this.page, param)
            },
            handleRefreshChange() {
                this.getList(this.page)
            },
            handleCreate() {
                this.$refs.crud.rowAdd()
            },
            handleOpenBefore(show, type) {
                window.boxType = type
                this.handleDept()
                this.getUnitListData()
                this.getPosListData()
                if (['edit', 'views'].includes(type)) {

                    this.org = []
                    this.form.deptId = this.form.deptId.toString()
                    for (var i = 0; i < this.form.orgList.length; i++) {
                        this.org[i] = this.form.orgList[i].id.toString()
                    }

                    fetchOrg().then(response => {
                        this.orgsOptions = response.data.data;
                    })
                    this.role = []
                    let list = []
                    console.log(this.form.roleId)
                    if(this.form.roleId){
                      list = this.form.roleId.split(',')
                    }
                    list.forEach(item => {
                        this.role.push(item * 1)
                    })
                    // this.role = parseInt(this.form.roleId).split(',')

                    console.log(this.role)
                    // for (var i = 0; i < this.form.roleList.length; i++) {
                    //     this.role[i] = this.form.roleList[i].roleId
                    // }
                    deptRoleList().then(response => {
                        this.rolesOptions = response.data.data
                    })
                } else if (type === 'add') {
                    this.org = []
                    this.role = []
                    this.posId
                }
                show()
            },
            orgUpdate(row) {
                let list = []
                row.orgList.forEach(item => {
                    list.push(item.id)
                })
                this.userId = row.id
                this.checkedKeys = list
                fetchOrg().then(response => {
                    this.treeData = response.data.data
                    // 解析出所有的太监节点
                    this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
                    this.dialogPermissionVisible = true
                    this.roleId = row.roleId
                    this.roleCode = row.roleCode
                })
            },
            /**
             * 解析出所有的太监节点id
             * @param json 待解析的json串
             * @param idArr 原始节点数组
             * @param temp 临时存放节点id的数组
             * @return 太监节点id数组
             */
            resolveAllEunuchNodeId(json, idArr, temp) {
                for (let i = 0; i < json.length; i++) {
                    const item = json[i]
                    // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
                    if (item.children && item.children.length !== 0) {
                        this.resolveAllEunuchNodeId(item.children, idArr, temp)
                    } else {
                        temp.push(idArr.filter(id => id == item.id))
                    }
                }
                return temp
            },
            handleUpdate(row, index) {
                this.$refs.crud.rowEdit(row, index)
                //this.form.password = undefined
            },
            cancal() {
                this.dialogPermissionVisible = false;
            },
            create(row, done, loading) {
                if (this.form.phone.indexOf('*') > 0) {
                    this.form.phone = undefined
                }
                let _form = {
                    org: this.org
                }

                let form = JSON.parse(JSON.stringify(this.form))
                form.jobType = form.jobType.join(',')
                form = {...form}
                addObj(form).then(() => {
                    this.getList(this.page)
                    done()
                    this.$notify({
                        title: '成功',
                        message: '创建成功',
                        type: 'success',
                        duration: 2000
                    })
                }).catch(() => {
                    loading()
                })
            },
            update(row, index, done, loading) {
                if (this.form.phone && this.form.phone.indexOf('*') > 0) {
                    this.form.phone = undefined
                }
                let form = JSON.parse(JSON.stringify(this.form))
                form.jobType = form.jobType.join(',')
                form = {...form}
                putObj(form).then(() => {
                    this.getList(this.page)
                    done()
                    this.$notify({
                        title: '成功',
                        message: '修改成功',
                        type: 'success',
                        duration: 2000
                    })
                }).catch(() => {
                    loading()
                })
            },
            updatePermession(userId) {
                this.orgIds = ''
                this.orgIds = this.$refs.orgTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.orgTree.getHalfCheckedKeys()
                    .join(','))
                let data = {
                    id: userId,
                    org: this.orgIds.split(',')
                }
                updateUserOrg(data).then(() => {
                    this.dialogPermissionVisible = false
                    this.getList(this.page)
                    this.$notify.success('修改成功')

                })
            },
            filterNode(value, data) {
                if (!value) return true
                return data.label.indexOf(value) !== -1
            },
            deletes(row, index) {
                this.$confirm(
                    '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
                    '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    delObj(row.id)
                        .then(() => {
                            this.list.splice(index, 1)
                            this.$notify({
                                title: '成功',
                                message: '删除成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                        .cache(() => {
                            this.$notify({
                                title: '失败',
                                message: '删除失败',
                                type: 'error',
                                duration: 2000
                            })
                        })
                })
            },
            valueToName(value){
                let list = []
                if(value && value.length){
                    value.forEach(item => {
                        let obj = {}
                        obj = this.jobTypeOptions.find(item1 => {
                            if(item1.id == item){
                                return item1
                            }
                        })
                        if(obj && obj.jobName){
                            list.push(obj.jobName)
                        }
                    })
                }
                return list.join(',')
            }
        }
    }
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>
